// pages/activities/activities.ts
import { MerchantAPI } from '../../utils/api'
import { CouponBinding } from '../../types/coupon'

interface CouponDisplay extends CouponBinding {
  // 扩展显示字段
  scopeText: string;
  statusText: string;
}

Page({
  data: {
    loading: false,
    refreshing: false,
    coupons: [] as CouponDisplay[],
    pageNum: 1,
    pageSize: 10,
    hasMore: true
  },

  onLoad() {
    this.loadCoupons();
  },

  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      hasMore: true
    });
    this.loadCoupons(true);
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        pageNum: this.data.pageNum + 1
      });
      this.loadCoupons();
    }
  },

  async loadCoupons(refresh: boolean = false) {
    if (this.data.loading) return;

    this.setData({ loading: true });

    try {
      const response = await MerchantAPI.getCouponList({
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize
      });

      if (response && response.code === 200) {
        const coupons = response.rows || [];
        const totalCount = response.total || 0;

        // 转换数据，添加显示字段
        const displayCoupons: CouponDisplay[] = coupons.map((coupon: CouponBinding) => ({
          ...coupon,
          scopeText: this.getScopeText(coupon.scope),
          statusText: coupon.status === 1 ? '启用' : '禁用'
        }));

        this.setData({
          coupons: refresh ? displayCoupons : [...this.data.coupons, ...displayCoupons],
          hasMore: this.data.coupons.length + displayCoupons.length < totalCount
        });
      } else {
        wx.showToast({
          title: response.msg || '加载失败',
          icon: 'none'
        });
      }
    } catch (error: any) {
      console.error('加载优惠券失败:', error);
      wx.showToast({
        title: error?.msg || '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
      if (refresh) {
        wx.stopPullDownRefresh();
      }
    }
  },

  // 获取适用范围文本
  getScopeText(scope: number): string {
    const scopeMap: Record<number, string> = {
      1: '全场通用',
      2: '指定商品',
      3: '指定分类'
    };
    return scopeMap[scope] || '未知';
  },

  // 创建优惠券
  createCoupon() {
    wx.navigateTo({
      url: '/pages/coupon-form/coupon-form'
    });
  },

  // 编辑优惠券
  editCoupon(e: any) {
    const coupon = e.currentTarget.dataset.coupon;
    wx.navigateTo({
      url: `/pages/coupon-form/coupon-form?bindingId=${coupon.bindingId}`
    });
  },

  // 切换优惠券状态
  async toggleCouponStatus(e: any) {
    const coupon: CouponDisplay = e.currentTarget.dataset.coupon;
    const newStatus = coupon.status === 1 ? 0 : 1;

    wx.showModal({
      title: '确认操作',
      content: `确定要${newStatus === 1 ? '启用' : '禁用'}该优惠券吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '处理中...' });

            const response = await MerchantAPI.updateCoupon({
              bindingId: coupon.bindingId,
              status: newStatus,
              merchantId: coupon.merchantId,
              couponId: coupon.couponId,
              scope: coupon.scope
            });

            if (response && response.code === 200) {
              wx.showToast({
                title: `${newStatus === 1 ? '启用' : '禁用'}成功`,
                icon: 'success'
              });
              // 刷新列表
              this.setData({ pageNum: 1 });
              this.loadCoupons(true);
            } else {
              wx.showToast({
                title: response.msg || '操作失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('切换优惠券状态失败:', error);
            wx.showToast({
              title: '操作失败',
              icon: 'none'
            });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },

  // 删除优惠券
  deleteCoupon(e: any) {
    const coupon: CouponDisplay = e.currentTarget.dataset.coupon;

    wx.showModal({
      title: '确认删除',
      content: '删除后将无法恢复，确定要删除该优惠券吗？',
      confirmColor: '#ff4444',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '删除中...' });

            const response = await MerchantAPI.deleteCoupon([coupon.bindingId]);

            if (response && response.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              // 刷新列表
              this.setData({ pageNum: 1 });
              this.loadCoupons(true);
            } else {
              wx.showToast({
                title: response.msg || '删除失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('删除优惠券失败:', error);
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },

  // 查看优惠券详情
  viewCouponDetail(e: any) {
    const coupon = e.currentTarget.dataset.coupon;
    wx.showToast({
      title: '查看详情功能开发中',
      icon: 'none'
    });
  }
});


